<?php
function save($DB_NAME,$username,$stock,$type,$value,$quality,$transactionDate){
	$db=new SQLiteDatabase($DB_NAME);
	$db->query("BEGIN;
	insert into stock_history(quality,stock,transaction_date,transaction_type,username,value) 
	values ($quality,'$stock','$transactionDate','$type','$username',$value);
	COMMIT;");
	if("Buy" == $type){
		$result=$db->query("SELECT * FROM residual_stock where username='$username' and stock ='$stock' and value=$value");
		if($result->valid()) {
			$row=$result->current();
			$db->query("BEGIN;
			update residual_stock set quality =quality +$quality where residual_stock_id=".$row['residual_stock_id'].";
			COMMIT;");
		}else{
			$db->query("BEGIN;
			insert into residual_stock(quality,stock,username,value) 
			values ($quality,'$stock','$username',$value);
			COMMIT;");
		}
	}else{
		$result=$db->query("SELECT * FROM residual_stock where username='$username' and stock ='$stock' order by value ASC");
		while($quality > 0 && $result->valid()) {
			$row=$result->current();
			if ($quality >= $row['quality']) {
				$db->query("BEGIN;
				delete from residual_stock where residual_stock_id=".$row['residual_stock_id'].";
				COMMIT;");
			} else {
				$db->query("BEGIN;
				update residual_stock set quality =quality-$quality where residual_stock_id=".$row['residual_stock_id'].";
				COMMIT;");
			}
			$quality = $quality - $row['quality'];
			$result->next();
		}
	}
}
?>